<template>
  <el-card class="main-card">
    <com-area title="查询条件">
      <template v-slot:main>
        <com-search
          ref="neuSearch"
          :config="searchParams.config"
          :formData="searchParams.formData"
          :buttons="searchParams.button"
          :searchLayoutParam="searchParams.searchLayoutParam"
        />
      </template>
    </com-area>
    <com-area
      title="用户列表"
      :loading="loading"
      :loading-size="1"
      :auto="true"
    >
      <template v-slot:toolbar>
        <com-toolBar :btnList="toolBarParams.btnList" />
      </template>
      <template v-slot:main>
        <com-table
          ref="table"
          :data="tableParams.tableData"
          :options="tableParams.options"
          :export="null"
          @search="search"
        />
      </template>
    </com-area>
    <!--新增修改对话框 -->
    <el-dialog :visible.sync="addOrEditModal" width="30%" top="9vh">
      <div class="dialog-title-container" slot="title" ref="userTitle" />
      <el-form label-width="80px" size="medium" :model="userForm" :rules="userFormRules" ref="userForm">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" style="width:250px" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" style="width:250px" />
        </el-form-item>
        <el-form-item label="角色">
          <el-select v-model="userForm.roleName" placeholder="请选择角色" >
            <el-option label="请选择角色" value="" />
            <el-option label="超级管理员" value="admin" />
            <el-option label="普通用户" value="user" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="addOrEditModal = false">取 消</el-button>
        <el-button type="primary" @click="resetPassword">
          重置密码
        </el-button>
        <el-button type="primary" @click="addOrUpdateUser">
          确 定
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { getUsers, getUserById, addUser, updateUser, deleteUser } from '@/api/system/user'
import searchParams from "./SearchParams";
import tableParams from "./TableParams";
import toolBarParams from "./ToolBarParams";
// 引入 CryptoJS
import CryptoJS from 'crypto-js';
export default {
  created() {
    this.search();
  },
  data: function() {
    return {
      searchParams: searchParams(this),
      tableParams: tableParams(this),
      toolBarParams: toolBarParams(this),
      loading: true,
      isDelete: false,
      currentPage: 1,
      pageSize: 10,
      addOrEditModal: false,
      addOrEditType: "",
      userForm: {
        id: "",
        username: "",
        password: "",
      },
      userFormRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" }
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" }
        ],
        roleName: [
          { required: true, message: "角色不能为空", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    search(reqParams) {
      console.log(reqParams);
      getUsers({
          currentPage: reqParams ? reqParams.currentPage : this.currentPage,
          pageSize: reqParams ? reqParams.pageSize : this.pageSize,
          username: reqParams? reqParams.username : ""
        })
        .then(({ data }) => {
          console.log(data);
          this.tableParams.options.currentPage = data.currentPage;
          this.tableParams.options.pageSize = data.pageSize;
          this.tableParams.options.total = data.total;
          this.tableParams.tableData = data.result;
          this.loading = false;
        });
    },
    openAddOrEditModel(user,type) {
      this.addOrEditType = type;
      this.$refs.userTitle.innerHTML = user ? "修改用户" : "新增用户";
      if (user != null) {
        this.userForm = JSON.parse(JSON.stringify(user));
      } else {
        this.userForm = {
          id: "",
          username: "",
          password: ""
        };
      }
      this.addOrEditModal = true;
    },
    async addOrUpdateUser() {
      let validateRes ;
      await this.$refs.userForm.validate((valid) => {
        if (valid) {
          validateRes = true;
        } else {
          return false;
        }
      });

      if (!validateRes) {
        return;
      }

      let params = {
        id: this.userForm.id,
        username: this.userForm.username,
        password: CryptoJS.MD5(this.userForm.password).toString(CryptoJS.enc.Hex)
      }
      // this.userForm.password = CryptoJS.MD5(this.userForm.password).toString(CryptoJS.enc.Hex);

      let result;
      if(this.addOrEditType === "add") {
        await addUser(params).then(data => {
          result = data;
        });
      }else{
        await updateUser(params).then(data => {
          result = data;
        });
      }
      if (result.flag) {
        this.$notify.success({
          title: "成功",
          message: result.message
        });
        this.search();
      } else {
        this.$notify.error({
          title: "失败",
          message: result.message
        });
      }
      this.addOrEditModal = false;
    },
     resetPassword() {
      this.$confirm("确定要重置密码吗？")
       .then(async () => {
         let params = {
           id: this.userForm.id,
           username: this.userForm.username,
           password: CryptoJS.MD5(this.userForm.password)
         };
         console.log(params.password);
         let result;
         await updateUser(this.userForm).then(data => {
           result = data;
         });
         if (result.flag) {
           this.$notify.success({
             title: "成功",
             message: result.message
           });
           this.search();
         } else {
           this.$notify.error({
             title: "失败",
             message: result.message
           });
         }
         this.addOrEditModal = false;
         this.$message.success("密码重置成功");
       })
       .catch(() => {});
    }
  }
};
</script>
<style scoped></style>
